import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {Button, Table, Icon, Divider, Popconfirm, Spin, Modal, Form, Input, Cascader, Radio, Card, message} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import addressList from "@/assets/provinceAndCityAndArea.json";
import busShopService from "@/services/busShop";

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
}

const map = {
  'FREE': '包邮',
  'PAY': '到付',
  'SELF': '自提',
}

@connect(({ giveback, loading }) => ({
  ...giveback,
  loading: loading.models.giveback,
}))
@Form.create()
class GivebackList extends PureComponent {
  state = {
    visible: false,
    loading: false,
    tableData: [],
    detail: {},
    title: ''
  }

  columns = [
    {
      title: '手机号',
      dataIndex: 'telephone',
    },
    {
      title: '收货地址',
      dataIndex: 'street',
      render: (text, record) => `${record.provinceStr}${record.cityStr}${record.areaStr}${text}`,
    },
    {
      title: '收货人',
      dataIndex: 'name',
    },
    {
      title: '归还快递',
      width: 100,
      dataIndex: 'freightType',
      render: (text, record) => map[text],
    },
    {
      title: '添加时间',
      width: 120,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 120,
      render: (_, record) => (
        <div>
          <a onClick={() => this.edit(record)}>
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm title="是否删除该归还地址？" onConfirm={() => this.handleDelete(record)}>
            <a>
              删除
            </a>
          </Popconfirm>
        </div>
      ),
    },
  ];


  componentWillMount() {
    this.getList()
  }

  handleDelete = record => {
    busShopService.delShopGiveBackAddressById({
      id: record.id
    }).then(res => {
      message.success('删除成功')
      this.getList()
    })
  };

  getList = () => {
    this.setState({
      loading: true,
    });
    busShopService.selectShopRuleAndGiveBackByShopId().then(res => {
      console.log(res);
      const data = res.data || res;
      this.setState({
        tableData: data || [],
      });
    }).finally(() => {
      this.setState({
        loading: false,
      });
    })
  }

  handleAdd = () => {
    const { form} = this.props;
    this.setState({
      visible: true,
      title: '新增归还地址'
    });
    form.resetFields();
  };

  edit = (record) => {
    this.setState({
      visible: true,
      detail: record,
      title: '修改归还地址'
    });
  };

  handleSubmit = e => {
    const { form, currentId, dispatch } = this.props;
    const { detail, title } = this.state

    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const obj = {
        provinceId: Number(fieldsValue.address[0]),
        cityId: Number(fieldsValue.address[1]),
        areaId: Number(fieldsValue.address[2]),
        ...detail,
        ...fieldsValue,
      };
      const service = detail.id ? busShopService.updateShopGiveBackAddressById:
        busShopService.saveShopGiveBackAddress
      service(obj).then(res => {
        message.success('新增成功')
        this.handleCancel()
        this.getList()
      })
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      detail: {}
    });
  };

  validateAddress = (_rule, value, callback) => {
    if (!value || !value[0] || !value[1] || !value[2]) {
      callback('请选择归还地址所在省市区');
      return;
    }
    callback();
  };

  render() {
    const { visible, loading, tableData, detail, title } = this.state
    const {form: { getFieldDecorator },} = this.props;
    let address = [];
    if (detail.provinceId && detail.cityId && detail.areaId) {
      address = [String(detail.provinceId), String(detail.cityId), String(detail.areaId)];
    }
    return (
      <PageHeaderWrapper title={false}>
        <Spin spinning={loading}>
          <Card bordered={false} style={{marginTop:20}}>
            <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: '30px' }}>
              新增归还地址
            </Button>
            <Table
              rowKey="id"
              columns={this.columns}
              dataSource={tableData}
              pagination={false}
            />
          </Card>
        </Spin>
        <Modal
          title={title}
          visible={visible}
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
          width={552}
        >
          <Form>
            <FormItem {...formItemLayout} label={<span>收货人姓名</span>}>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入收货人姓名', whitespace: true }],
                initialValue: detail.name || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>
            <Form.Item {...formItemLayout} label="所属区域" required>
              {getFieldDecorator('address', {
                rules: [
                  {
                    validator: this.validateAddress,
                  },
                ],
                initialValue: address,
              })(<Cascader options={addressList} placeholder="请选择" />)}
            </Form.Item>
            <FormItem {...formItemLayout} label={<span>详细地址</span>}>
              {getFieldDecorator('street', {
                rules: [{ required: true, message: '请输入详细地址', whitespace: true }],
                initialValue: detail.street || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>

            <FormItem {...formItemLayout} label={<span>归还快递</span>}>
              {getFieldDecorator('freightType', {
                initialValue: detail.freightType || 'PAY',
              })(<Radio.Group>
                <Radio value={'FREE'}>包邮</Radio>
                <Radio value={'PAY'}>到付</Radio>
                {/*<Radio value={'SELF'}>自提</Radio>*/}
              </Radio.Group>)}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>手机号码</span>}>
              {getFieldDecorator('telephone', {
                rules: [{ required: true, pattern: new RegExp(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/, "g") , message: '请输入正确的手机号' }],
                initialValue: detail.telephone || '',
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default GivebackList;
